package gl.java.sms;

import gl.java.sms.bean.SmsBean;
import gl.java.sms.util.Result;
import gl.java.sms.util.TextUtils;

import java.util.ArrayList;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sun.jersey.spi.resource.Singleton;
/**
 * 短信发送机的回调接口，短信被客户端发送成功后，服务器从待发送短信列表中移除短信任务
 * @author Administrator
 *
 */
@Path("/sentcallback")
@Singleton
public class SMS {
	/**
	 * 计数器：收到的短信数量
	 */
	private static int count_receive=0;
	/**
	 * 计数器：发出的短信数量
	 */
	private static int count_send=0;
	/**
	 * 计数器：送达的短信数量
	 */
	private static int count_sent=0;
	
	private static ArrayList<SmsBean> list = new ArrayList<SmsBean>();
	/**
	 * 得到队列中待发送的短信的数量
	 * @return
	 */
	public static int getCountOfWaitingSend(){
		return list.size();
	}
	@GET
	@Path("/count")
	public static String getCount(){
		JsonObject msg_content = new JsonObject();
		msg_content.addProperty("count_receive", count_receive);
		msg_content.addProperty("count_send",count_send);
		msg_content.addProperty("count_sent", count_sent);
		return Result.formatJson(true, msg_content.toString(), null);
	}
	/**
	 * 客户端发送短信成功回调方法
	 * @param smsid
	 * @param token
	 * @return
	 */
	@GET
	public String getesms(
			@DefaultValue("-1") @QueryParam("smsid") String smsid,
			@QueryParam("token") String token) {
		Logger.getLogger("callback").info("sms callback"+token+":"+smsid);
		if (TextUtils.isEmpty(token) /*||!isLogin(token)*/) {
			return Result.formatErrJson("Invalid Token,must login at first");
		}
		if (UserList.getUser(token)!=null) {
			UserList.getUser(token).setBusy(false);
		}
		
		if (TextUtils.isEmpty(smsid)) {
			return Result.formatErrJson("Invalid smsid");
		}
		try {
			if (!hasSmsId(Long.parseLong(smsid))) {
				return Result
						.formatErrJson("Invalid smsid,is not exist in waiting send list");
			}
		} catch (Exception e) {
			return Result.formatErrJson("Invalid smsid,it is long Interage");
		}
		removeWaitSms(Long.parseLong(smsid));
		return Result.formatJson(true, null, null);
	}
	@POST
	public String getesmsOnpost(
			@DefaultValue("-1") @QueryParam("smsid") String smsid,
			@QueryParam("token") String token) {
		return getesms(smsid, token);
	}

	synchronized static void removeWaitSms(long smsid) {
		SmsBean s = null;
		for (SmsBean iterable_element : list) {
			if (iterable_element.getId() == smsid) {
				s = iterable_element;
				s.setSent(true);
				s.setSendTime(System.currentTimeMillis());
				count_sent++;
				break;
			}
		}
		if (s != null) {
			list.remove(s);
			// TODO 持久化存储 已经发送成功的短信
			Logger.getLogger("remove:").error(":"+new Gson().toJson(s));
		}

	}

	public static boolean isLogin(String token) {
		return UserList.isHasThisToken(token);
	}

	private boolean hasSmsId(long smsid) {
		for (SmsBean iterable_element : list) {
			if (iterable_element.getId() == smsid) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 添加一条待发送短信到队列
	 * 
	 * @param tel
	 * @param conent
	 * @return
	 */
	public synchronized static SmsBean addWatiingSendSms(String tel,
			String conent) {
		SmsBean mSmsBean = new SmsBean();
		mSmsBean.setContent(conent);
		mSmsBean.setTel(tel);
		mSmsBean.setSent(false);
		mSmsBean.setId(System.currentTimeMillis());
		mSmsBean.setCreateTime(System.currentTimeMillis());
		list.add(mSmsBean);
		// TODO 持久化存储待发送成功的短信
		Logger.getLogger("add:").error(":"+new Gson().toJson(mSmsBean));
		count_receive++;
		return mSmsBean;
	}

	public static void taskLoop() {
//		Logger.getLogger("SMS:TaskLoop").info("CountOfWaitingSend:"+getCountOfWaitingSend());
//		for (SmsBean iterable_element : list) {
//			if (!iterable_element.isSent()
//					&& iterable_element.getCreateTime() + 60 * 1000 < System
//							.currentTimeMillis()) {
//				SendSms.pushSmsTask(iterable_element.getTel(),
//						iterable_element.getContent(), iterable_element.getId());
//			}
//		}
//		UserList.checkSmserIsOnline();
	}
	public static void main(String[] args) {
		Logger.getLogger("db").info("CountOfWaitingSend:"+getCountOfWaitingSend());
	}
	public static SmsBean getAWaitSms() {
		synchronized (list) {
			if (list.size()>0) {
				SmsBean sms = list.get(0);
				list.remove(0);
				count_send++;
				return sms;
			}
		}
		return null;
	}
}